package org.expath.httpclient.test.server;

import java.io.IOException;
import java.io.Reader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.expath.httpclient.test.server.TestRequest.Failure;

/**
 * ...
 *
 * @author Florent Georges
 */
public class TextBodyAsserter
        implements BodyAsserter
{
    public TextBodyAsserter(String content)
    {
        myContent = content;
    }

    public boolean assertIt(HttpServletRequest req, Failure f)
            throws ServletException
    {
        try {
            Reader in = req.getReader();
            StringBuilder buf = new StringBuilder();
            char[] chars = new char[4096];
            int len;
            while ( (len = in.read(chars)) > -1 ) {
                buf.append(chars, 0, len);
            }
            String content = buf.toString();
            if ( ! myContent.equals(content) ) {
                f.add("Content not correct: '" + content + "'");
                f.add("  expected: '" + myContent + "'");
                return false;
            }
            return true;
        }
        catch ( IOException ex ) {
            throw new ServletException(ex);
        }
    }

    private String myContent;
}
